package com.zjk.toolkit.governance.service.impl;

import com.alibaba.fastjson.JSON;
import com.zjk.toolkit.governance.annotations.DoWhiteList;
import com.zjk.toolkit.governance.config.WhiteListProperties;
import com.zjk.toolkit.governance.service.IGovernanceService;
import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class WhiteListServiceImpl implements IGovernanceService {

    private static final Logger logger = LoggerFactory.getLogger(WhiteListServiceImpl.class);

    private final WhiteListProperties properties;

    public WhiteListServiceImpl(WhiteListProperties properties) {
        this.properties = properties;
    }

    @Override
    public Object access(ProceedingJoinPoint joinPoint, Method method, Annotation annotation, Object[] args) throws Throwable {
        if (annotation instanceof DoWhiteList) {
            String keyValue = getFiledValue(((DoWhiteList) annotation).key(), joinPoint.getArgs());
            logger.info("whitelist handler method：{} value：{}", method.getName(), keyValue);
            if (null == keyValue || keyValue.isEmpty()) {
                return joinPoint.proceed();
            }

            String[] split = properties.getUsers().split(",");

            // 白名单过滤
            for (String str : split) {
                if (keyValue.equals(str)) {
                    return joinPoint.proceed();
                }
            }

            // 拦截
            return returnObject((DoWhiteList)annotation, method);
        }
        return joinPoint.proceed();
    }

    private Object returnObject(DoWhiteList annotation, Method method) {
        if (null != annotation.returnJson() && !annotation.returnJson().isEmpty()) {
            return JSON.parseObject(annotation.returnJson(),method.getReturnType());
        } else {
            return null;
        }
    }

    private String getFiledValue(String filed, Object[] args) {
        String filedValue = null;
        for (Object arg : args) {
            try {
                if (null == filedValue || filedValue.isEmpty()) {
                    filedValue = BeanUtils.getProperty(arg, filed);
                } else {
                    break;
                }
            } catch (Exception e) {
                if (args.length == 1) {
                    return args[0].toString();
                }
            }
        }
        return filedValue;
    }
}
